const { User, FileFolder } = require('../model')
const { generateAccessToken, generateRefreshToken } = require('../utils/token')
const { verify } = require('../utils/jwt')

exports.login = async (req, res, next) => {
  try {
    const user = await User.findById(req.user._id)
    if (user) {
      const accessToken = await generateAccessToken({ id: user._id });
      const refreshToken = await generateRefreshToken({ id: user._id });
      res.json({ code: 200, accessToken, refreshToken, data: user });
    }
  } catch (err) {
    next(err);
  }
};
exports.getToken = async (req, res, next) => {
  try {
    const refreshToken = req.body.refreshToken;
    if (refreshToken == null) return res.sendStatus(401);
    const user = await verify(refreshToken, '8d7638fb-e72c-4226-890e-5bfae8e6bad4');
    const accessToken = await generateAccessToken({ id: user.id });
    res.json({ code: 200, accessToken })
  } catch (err) {
    res.sendStatus(403);
  }
}
// Registration 用户注册
exports.register = async (req, res, next) => {
  try {
    // 处理请求
    let user = new User(req.body.user)
    await user.save()
    let fileFolder = new FileFolder({ author: user._id });
    await fileFolder.save();
    user = user.toJSON()
    delete user.password
    delete user.token
    res.status(200).json({
      code: 200,
      data: user
    })
  } catch (err) {
    next(err);
  }
};

exports.userList = async (req, res, next) => {
  try {
    const { keyword } = req.query;
    let query = {}
    if (keyword) {
      query.username = { $regex: keyword, $options: 'i' };
    }
    const users = await User.find(query)
    res.status(200).json({ code: 200, data: users })
  } catch (err) {
    next(err);
  }
}

exports.userInfo = async (req, res, next) => {
  try {
    const user = await User.findById(req.query.id);
    if (!user) {
      return res.status(200).json({
        code: 404,
        data: '用户不存在'
      });
    }
    const friendDetails = await Promise.all(user.friendList.map(async (item) => {
      const friend = await User.findById(item);
      return { _id: friend._id, username: friend.username, email: friend.email, avatar: friend.avatar };
    }));
    user.friendList = friendDetails;
    res.status(200).json({
      code: 200,
      data: user
    });
  } catch (err) {
    next(err);
  }
};

exports.delFriend = async (req, res, next) => {
  try {
    const { userId, friendId } = req.body;
    const user = await User.findById(userId);
    let userIndex = user.friendList.indexOf(friendId);
    user.friendList.splice(userIndex, 1);
    await user.save();
    if (!user) {
      return res.status(200).json({
        code: 404,
        data: '用户不存在'
      });
    }
    let friend = await User.findById(friendId);
    let friendIndex = friend.friendList.indexOf(userId);
    friend.friendList.splice(friendIndex, 1);
    await friend.save()
    res.status(200).json({
      code: 200,
      data: '删除好友成功'
    });
  } catch (err) {
    next(err);
  }
}

